﻿using JNPF.Basics.Models;
using JNPF.Utils;
using System;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 公众号素材
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-09-18 
    public class MPMaterialBll
    {
        private MPMaterialIService service = new MPMaterialService();
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="type">素材类型</param>
        /// <param name="requestParam">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<MPMaterialEntity>> GetList(int type, PageInput input)
        {
            try
            {
                return await service.GetList(type, input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 素材信息
        /// </summary>
        /// <param name="mediaId">公众号素材Id</param>
        /// <returns></returns>
        public async Task<MPMaterialEntity> GetInfo(string mediaId)
        {
            try
            {
                return await service.GetInfo(mediaId);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 上传永久素材(图片（image）、语音（voice）和缩略图（thumb）)
        /// </summary>
        /// <param name="filejson">绝对路径</param>
        public async Task<string> UploadForeverMedia(MPMaterialEntity entity)
        {
            try
            {
                var config = await new SysConfigBll().GetInfo("MPConfig");
                var filePath = ConfigurationKey.MPMaterialFilePath + entity.FileJson;
                var resultJObject = new WeChatMPHelper(config.WX_GZH_APPID, config.WX_GZH_APPSECRET).UploadForeverMedia(filePath).ToObject();
                var errcode = resultJObject["errcode"].ToString();
                if (errcode == "0")
                {
                    entity.MediaId = resultJObject["mediaid"].ToString();
                    entity.ReturnUrl = resultJObject["url"].ToString();
                    entity.EnabledMark = errcode.ToInt();
                    entity.Description = errcode == "0" ? "" : resultJObject["errmsg"].ToString();
                    entity.Id = CommonHelper.Guid;
                    entity.SortCode = CommonHelper.SortCode;
                    entity.UploadUser = UserProvider.Instance.Get().UserId;
                    entity.UploadDate = DateTime.Now;
                    //if (entity.MaterialsType != 5)
                    await service.Create(entity);
                    //var materialPath = ConfigurationKey.MPMaterialFilePath + entity.FileJson;
                    // FileHelper.Copy(filePath, materialPath);
                    return entity.MediaId;
                }
                else
                {
                    throw new Exception(resultJObject.ToJson());
                }
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 上传永久视频素材
        /// </summary>
        /// <param name="entity">实体对象</param>
        public async Task<string> UploadForeverVideo(MPMaterialEntity entity)
        {
            try
            {
                var config = await new SysConfigBll().GetInfo("MPConfig");
                var filePath = ConfigurationKey.TemporaryFilePath + entity.FileJson;
                var resultJObject = new WeChatMPHelper(config.WX_GZH_APPID, config.WX_GZH_APPSECRET).UploadForeverVideo(filePath, entity.Title, entity.Introduction).ToObject();
                var errcode = resultJObject["errcode"].ToString();
                if (errcode == "0")
                {
                    entity.MediaId = resultJObject["mediaid"].ToString();
                    entity.ReturnUrl = resultJObject["url"].ToString();
                    entity.EnabledMark = errcode.ToInt();
                    entity.Description = errcode == "0" ? "" : resultJObject["errmsg"].ToString();
                    entity.Id = CommonHelper.Guid;
                    entity.SortCode = CommonHelper.SortCode;
                    entity.UploadUser = UserProvider.Instance.Get().UserId;
                    entity.UploadDate = DateTime.Now;
                    await service.Create(entity);
                    var materialPath = ConfigurationKey.MPMaterialFilePath + entity.FileJson;
                    FileHelper.Copy(filePath, materialPath);
                    return entity.MediaId;
                }
                else
                {
                    throw new Exception(resultJObject.ToJson());
                }
            }
            catch (ExceptionEx ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 上传永久图文素材
        /// </summary>
        /// <param name="entity">实体对象</param>
        public async Task<string> UploadNews(MPMaterialEntity entity)
        {
            try
            {
                var config = await new SysConfigBll().GetInfo("MPConfig");
                var thumbMediaId = await UploadForeverMedia(entity);
                MPMaterialModel materialModel = new MPMaterialModel();
                materialModel.title = entity.Title;
                materialModel.author = entity.Author;
                materialModel.content = entity.Content;
                materialModel.content_source_url = entity.ContentSourceUrl;
                materialModel.digest = entity.Digest;
                materialModel.need_open_comment = entity.NeedOpenComment.ToInt();
                materialModel.only_fans_can_comment = entity.OnlyFansCanComment.ToInt();
                materialModel.show_cover_pic = "1";
                materialModel.thumb_media_id = thumbMediaId;
                var resultNewsJObject = new WeChatMPHelper(config.WX_GZH_APPID, config.WX_GZH_APPSECRET).UploadNews(materialModel).ToObject();
                var errcode = resultNewsJObject["errcode"].ToString();
                if (errcode == "0")
                {
                    entity.ThumbMediaId = thumbMediaId;
                    entity.MediaId = resultNewsJObject["mediaid"].ToString();
                    entity.ShowCoverPic = materialModel.show_cover_pic;
                    entity.NeedOpenComment = materialModel.need_open_comment;
                    entity.OnlyFansCanComment = materialModel.only_fans_can_comment;
                    entity.ReturnUrl = resultNewsJObject["url"].ToString();
                    entity.EnabledMark = errcode.ToInt();
                    entity.Description = errcode == "0" ? "" : resultNewsJObject["errmsg"].ToString();
                    entity.Id = CommonHelper.Guid;
                    entity.SortCode = CommonHelper.SortCode;
                    entity.UploadUser = UserProvider.Instance.Get().UserId;
                    entity.UploadDate = DateTime.Now;
                    await service.Create(entity);
                    return entity.MediaId;
                }
                else
                {
                    throw new Exception(resultNewsJObject.ToJson());
                }
            }
            catch (ExceptionEx ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 删除永久素材
        /// </summary>
        /// <param name="entity">实体对象</param>
        public async Task DeleteForeverMedia(MPMaterialEntity entity)
        {
            try
            {
                var config = await new SysConfigBll().GetInfo("MPConfig");
                var filePath = ConfigurationKey.MPMaterialFilePath + entity.FileJson;
                new WeChatMPHelper(config.WX_GZH_APPID, config.WX_GZH_APPSECRET).DeleteForeverMedia(entity.MediaId);
                await service.Delete(entity);
                FileHelper.DeleteFile(filePath);
            }
            catch (ExceptionEx ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
    }
}
